<template>
	<view class="contract uni-flex-column" :style="bgStyle">
		<CustomNavBar class="navbar" title="">
			<template v-slot:left>
				<view class="back uni-flex uni-align-center uni-justify-center" @click="goBack">
					<uni-icons type="left" size="20"></uni-icons>
				</view>
			</template>
		</CustomNavBar>

		<view class="content">
			<view class="box-top">
				<view class="top-left">
					<text class="text1">百城运营</text>
					<text class="text2">千城千面，服务无界</text>
				</view>
				<view class="right-left">
					<image :src="`${$ImgBaseUrl}baichengyunying-icon.png`" class="baichengyunying-icon" />
				</view>
			</view>

			<!-- 表单部分 -->
			<view class="form-container">
				<form @submit="submitForm">
					<view class="form-item">
						<view class="label-box">
							<text class="required">*</text>
							<text class="label">姓名</text>
						</view>
						<uni-easyinput v-model="formData.name" placeholder="请输入姓名" :inputBorder='false'
							:clearable='false'></uni-easyinput>
					</view>

					<view class="form-item">
						<view class="label-box">
							<text class="required">*</text>
							<text class="label">证件类型</text>
						</view>
						<!-- 修改picker的range为对象数组 -->
						<picker mode="selector" :range="idTypes" :range-key="'name'" @change="handleIdTypeChange">
							<view class="picker input">
								<text class="picker-placeholder" v-if="!formData.cardTypeText">{{ '请选择证件类型' }}</text>
								<text class="picker-text">{{ formData.cardTypeText }}</text>
								<uni-icons type="down" size="12" color="#666666"></uni-icons>
							</view>
						</picker>
					</view>

					<view class="form-item">
						<view class="label-box">
							<text class="required">*</text>
							<text class="label">身份证号</text>
						</view>
						<uni-easyinput v-model="formData.cardCode" placeholder="请输入身份证号" :inputBorder='false'
							:clearable='false'></uni-easyinput>
					</view>

					<view class="form-item">
						<view class="label-box">
							<text class="required">*</text>
							<text class="label">联系方式</text>
						</view>
						<uni-easyinput v-model="formData.phone" placeholder="请输入联系方式" :inputBorder='false'
							:clearable='false'></uni-easyinput>
					</view>

					<view class="form-item">
						<view class="label-box">
							<text class="required">*</text>
							<text class="label">当前住址</text>
						</view>
						<uni-easyinput v-model="formData.address" placeholder="请输入当前住址" :inputBorder='false'
							:clearable='false'></uni-easyinput>
					</view>

					<view class="form-item">
						<view class="label-box">
							<text class="required">*</text>
							<text class="label">服务区域</text>
						</view>
						<uni-data-picker placeholder="请选择服务区域" popup-title="请选择所在地区" :localdata="dataTree"
							v-model="formData.serverArea" @change="onAddressChange" @nodeclick="onNodeClick">
						</uni-data-picker>
					</view>
				</form>
			</view>
			<button formType="submit" class="submit-btn" @click="handleSubmit">提交</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import CustomNavBar from "@/components/custom-navbar/index.vue";
	import {
		AddappOpe
	} from '@/api/BaichengOperations.js'
	import {
		ImgBaseUrl
	} from '@/utils/domain.js'
	import {
		domicileAddressApi,
	} from '@/api/personalData.js'
	const bgStyle = computed(() => ({
		backgroundImage: `url(${ImgBaseUrl}baichengyunying-bg.png)`,
	}));

	// 修改证件类型为对象数组（包含显示文本和后端需要的value）
	const idTypes = ref([{
			name: '身份证',
			value: 'ID_CARD'
		}
		// 可在此处添加其他证件类型，如：
		// { name: '护照', value: 'PASSPORT' }
	]);
	const serverArea = ref(['北京', '上海', '广州', '深圳']);
	const dataTree = ref();
	const formData = ref({
		id: '',
		name: '',
		cardTypeText: '', // 用于页面显示的证件类型文本
		cardType: '', // 用于传给后端的证件类型ID（如ID_CARD）
		cardCode: '',
		phone: '',
		address: '',
		serverArea: '',
	});

	onMounted(() => {
		try {
			const userInfoStr = uni.getStorageSync('user_info');
			if (userInfoStr) {
				const userInfo = JSON.parse(userInfoStr);
				if (userInfo.id) {
					formData.value.id = userInfo.id;
					console.log('成功获取用户ID:', userInfo.id);
				} else {
					console.warn('用户信息中不包含id字段');
				}
			} else {
				console.warn('本地存储中未找到user_info');
			}
		} catch (error) {
			console.error('获取本地用户信息失败:', error);
		}
		domicileAddressApi().then((res) => {
			if (res.code === 200) {
				dataTree.value = res.data;
			}
		});
	});

	// 修改证件类型选择逻辑：显示name，存储value
	const handleIdTypeChange = (e) => {
		const selectedIndex = e.detail.value;
		formData.value.cardTypeText = idTypes.value[selectedIndex].name; // 页面显示文本
		formData.value.cardType = idTypes.value[selectedIndex].value; // 传给后端的ID
	};

	const handleserverAreaChange = (e) => {
		formData.value.serverArea = serverArea.value[e.detail.value];
	};

	const submitForm = () => {
		console.log('提交的表单数据:', formData.value);
	};

	const handleSubmit = () => {
		// 表单验证
		if (!formData.value.name) {
			return uni.showToast({
				title: '请输入姓名',
				icon: 'none'
			});
		}
		if (!formData.value.cardType) { // 验证后端需要的字段
			return uni.showToast({
				title: '请选择证件类型',
				icon: 'none'
			});
		}
		if (!formData.value.cardCode) {
			return uni.showToast({
				title: '请输入证件号码',
				icon: 'none'
			});
		}
		if (!formData.value.phone) {
			return uni.showToast({
				title: '请输入联系方式',
				icon: 'none'
			});
		}
		if (!formData.value.address) {
			return uni.showToast({
				title: '请输入当前住址',
				icon: 'none'
			});
		}
		if (!formData.value.serverArea) {
			return uni.showToast({
				title: '请选择服务区域',
				icon: 'none'
			});
		}

		// 提交时formData.cardType已自动包含ID_CARD
		AddappOpe(formData.value).then((res) => {
			console.log('提交结果:', res);
			uni.showToast({
				title: res.msg || '提交成功',
				icon: 'success'
			});
			setTimeout(() => {
				goBack();
			}, 1500);
		}).catch((err) => {
			console.error('提交失败:', err);
			uni.showToast({
				title: err.msg || '提交失败，请稍后重试',
				icon: 'none'
			});
		});
	}

	const onAddressChange = (e) => {};
	const onNodeClick = (node) => {
		console.log('节点点击:', node);
	};
	const goBack = () => {
		uni.navigateBack({
			delta: 1
		});
	}
</script>

<style scoped lang="scss">
	/* 样式部分保持不变 */
	.contract {
		height: 100vh;
		background-repeat: no-repeat;
		background-position: top center;

		.navbar {
			width: 100%;
		}

		.back {
			width: 44rpx;
			height: 44rpx;
			background: rgba(255, 255, 255, 0.6);
			border-radius: 50%;
		}

		.content {
			padding: 20rpx;
			box-sizing: border-box;
			height: calc(100% - 100rpx);

			.box-top {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.top-left {
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					height: 120rpx;

					.text1 {
						font-size: 50rpx;
						color: #0759C7;
						font-weight: bold;
					}

					.text2 {
						font-size: 28rpx;
						color: #0759C7;
						font-weight: 400;
					}
				}

				.right-left {
					width: 272rpx;
					height: 168rpx;

					.baichengyunying-icon {
						width: 100%;
						height: 100%;
					}
				}
			}

			.form-container {
				margin-top: 30rpx;
				background-color: #fff;
				border-radius: 20rpx;
				padding: 30rpx;
				box-sizing: border-box;

				.form-item {
					margin-bottom: 20rpx;

					.label-box {
						display: flex;
						margin-bottom: 15rpx;

						.required {
							color: #FF6A47;
							margin-right: 5rpx;
							font-size: 28rpx;
						}

						.label {
							display: block;
							font-size: 28rpx;
							color: #303133;
							margin-bottom: 10rpx;
							font-weight: 400;
						}
					}

					.picker {
						width: 100% !important;
						height: 88rpx;
						background: #F3F6FC;
						border-radius: 20rpx;
						padding: 0 20rpx;
						box-sizing: border-box;
						font-size: 28rpx;
						display: flex;
						justify-content: space-between;
						align-items: center;

						.picker-placeholder {
							color: #999999;
							font-size: 28rpx;
							font-weight: 400;
						}

						.picker-text {
							font-size: 28rpx;
							font-weight: 400;
						}
					}
				}
			}

			.submit-btn {
				margin-top: 40rpx;
				height: 88rpx;
				line-height: 88rpx;
				background: #2F80ED;
				color: #fff;
				border-radius: 44rpx;
				font-size: 30rpx;
				font-weight: 500;
			}
		}
	}

	::v-deep .uni-easyinput__content {
		width: 100% !important;
		height: 88rpx !important;
		background: #F3F6FC !important;
		border-radius: 20rpx !important;
		box-sizing: border-box !important;
		font-size: 28rpx !important;
	}

	::v-deep .input-value-border {
		border: none !important;
	}

	::v-deep .input-value {
		height: 88rpx !important;
	}

	::v-deep .uni-data-tree {
		background: #F3F6FC !important;
		border-radius: 20rpx !important;
	}

	::v-deep .input-arrow {
		width: 12rpx;
		height: 12rpx;
		border-left: 1rpx solid #666;
		border-bottom: 1rpx solid #666;
	}
</style>